$(function(){
    bky.checkUpdate = function(){
        $.get("http://www.cnblogs.com/liulun/articles/7710391.html",function(r){
            var trueVersion = $(r).find("#51cnblogsVersion").html();
            trueVersion = parseInt($.trim(trueVersion));
            if(bky.version < trueVersion){
                alert("有新版本，您需要升级");
                nw.Shell.openExternal('https://gitee.com/xland/cnblogs/releases');
            }
        })
    }
    bky.showLogin = function(){
        $("body").append(bky.loginDiv);
        $("#loginFrame").on("load",function(){
            var frame = document.getElementById('loginFrame').contentWindow;
            var testDom = frame.$("#app_ing");
            if(testDom.length > 0 && testDom.html() == "闪存"){
                $("#loginFrame").parent().remove();
            }
        })
    }
    bky.checkLogin = function(){
        $.get("https://i.cnblogs.com/",function(r){
            var dom = $(r).find("#TabPosts");
            if(dom.length>0 && dom.hasClass("current_nav")){
                return;
            }
            bky.showLogin();
        })
    }
    bky.editArticleHandler = function(){
        //https://i.cnblogs.com/PostDone.aspx?postid=7681073&actiontip=%e4%bf%9d%e5%ad%98%e4%bf%ae%e6%94%b9%e6%88%90%e5%8a%9f
        var frame = document.getElementById('articleFrame').contentWindow;
        var msg = frame.location.href.split('=');
        msg = msg[msg.length -1];
        msg = decodeURI(msg);
        if(msg == "保存修改成功" || msg == '发布成功' || msg == '保存草稿成功'){
            var url = 'https://i.cnblogs.com/'+frame.$("#TipsPanel_LinkEdit").attr("href");
            frame.location.href = url;
            alert("保存成功");
            return;
        }
        setTimeout(function(){
            var title = frame.$("#Editor_Edit_txbTitle").val();
            var content = frame.$('#Editor_Edit_EditorBody').val();
            UE.getEditor('editor').setContent(content);
            if(frame.$("#Editor_Edit_lkbDraft").length>0){
                $("#saveBtn").show();
            }else{
                $("#saveBtn").hide();
            }
            if($("#articleFrame").attr("src") == 'https://i.cnblogs.com/EditPosts.aspx?opt=1'){
                $("#newBtn").hide();
            }else{
                $("#newBtn").show();
            }
            $("#titleInput").val(title);
            $("#articleListBg").hide();
        },600);    
    }
    bky.editArticle = function(){
        $("#articleListWrapper").hide();
        var id = $(this).attr("id");
        $("#articleFrame").attr("src",'https://i.cnblogs.com/EditPosts.aspx?postid='+id);
    }
    bky.newArticle = function(){
        if($("#titleInput").val().length > 0 || UE.getEditor('editor').getContent().length > 0){
            var flag = confirm("您现在处于编辑文章的状态，确实要退出吗？");
            if(!flag){
                return;
            }        
        }
        $("#articleListBg").show();
        $("#articleListWrapper").hide();
        $("#articleFrame").attr("src",'https://i.cnblogs.com/EditPosts.aspx?opt=1');
    }
    
    bky.saveArticle = function(btnId){    
        var obj = {};
        obj.title = $("#titleInput").val();
        obj.content = UE.getEditor('editor').getContent();
        obj.content = '<div class="liulunEditor" style="font-family: Microsoft YaHei;">'+obj.content+'</div>';
        if(obj.title.length < 2||obj.content.length < 6){
            alert("文章标题或者文章正文字数太少");
            return;
        }
        $("#articleListBg").show();
        $("#articleListWrapper").hide();
        var frame = document.getElementById('articleFrame').contentWindow;
        frame.$("#Editor_Edit_txbTitle").val(obj.title);
        //frame.$('#Editor_Edit_EditorBody').val(obj.content);
        //frame.tinyMCE.activeEditor.setContent(obj.content);
        frame.blogEditor.setContent(obj.content);
        //frame.tinyMCE.execCommand('mceInsertContent', false, obj.content);
        frame.$("#"+btnId).click();
    }
    bky.uploadImg = function(event,cb){
        var items = event.clipboardData.items;
        if(items[0].type.indexOf("image") < 0){
            return;
        }
        var file = items[0].getAsFile();
        var formData = new FormData();
        formData.append('imageFile', file);
        formData.append("mimeType", file.type);
        var frame = document.getElementById('articleFrame').contentWindow
        frame.$.ajax({
            type: 'POST',
            url:bky.imgUploadUrl,
            data: formData,
            processData: false, 
            contentType: false, 
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            success: function(result) {
                if(result.success){
                    var img = '<img src="' + result.message + '" />';
                    cb(img);
                }
            }
        });    
    }
    
    bky.getList = function(pageIndex){
        $.get("https://i.cnblogs.com/posts?page="+pageIndex,function(r){
            $("#articleListBg").show();
            var doc = $(r);
            if(!doc.find("#TabPosts")){
                bky.showLogin();
                return;
            }
            var lastPager = doc.find(".pager .current").html();
            if(parseInt(lastPager)<pageIndex){
                return;
            }
            $(".titleRow").remove();        
            doc.find(".post-title a").each(function(index,item){
                var id = $(item).attr("href").split('/');
                id = id[id.length-1]
                id = id.split('.')[0];
                var indexNum = index+1+(pageIndex-1)*30;
                var str = $(item).html();
                str = '<div class="titleRow" id="'+id+'">'+indexNum+':&nbsp;'+str+'</div>';
                if(index < 15){
                    $("#articleLeft").append(str);
                }else{
                    $("#articleRight").append(str);
                }            
            })
            $(".titleRow").click(bky.editArticle);
            bky.pageIndex = pageIndex;
            $("#articleListWrapper").show();
            
        })
    }
    bky.init = function(){        
        bky.checkUpdate();
        bky.checkLogin();
        var arr = bky.articleDiv.split('^');
        var dom = arr[0]+'https://i.cnblogs.com/EditPosts.aspx?opt=1'+arr[1];    
        $("body").append(dom);
        $("#articleFrame").on("load",bky.editArticleHandler);
    }
    bky.init();
})